package com.fht.spring_boot_study.config.shiro;

import com.fht.spring_boot_study.model.account.entity.Resource;
import com.fht.spring_boot_study.model.account.entity.Role;
import com.fht.spring_boot_study.model.account.entity.User;
import com.fht.spring_boot_study.model.account.service.ResourceService;
import com.fht.spring_boot_study.model.account.service.RoleService;
import com.fht.spring_boot_study.model.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        User user = (User) principals.getPrimaryPrincipal();
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(role -> {
            simpleAuthorizationInfo.addRole(role.getName());
            List<Resource> resources = resourceService.getResourcesByRoleId(role.getId());
            resources.stream().forEach(resource -> {
                simpleAuthorizationInfo.addStringPermission(resource.getPermission());
            });
        });

        // 资源授权器
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("The account do not exist.");
        }

        /**
         * 身份验证器
         * principal: 当前用户信息，可以是 user 对象，也可以是用户名
         * credentials: 当前用户凭证
         * realmName: 当前 realm 对象的唯一名字
         */
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}